package com.ws.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ws.common.authentication.JWTUtil;
import com.ws.entity.*;
import com.ws.mapper.*;
import com.ws.service.UserService;
import com.ws.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.*;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuRoleMApper menuRoleMapper;

    @Autowired
    private AddressMapper addressMapper;

    @Override
    public Result adminLogin(User user, HttpServletRequest request) {
        //根据用户名查询数据
        String uname = user.getUsername();
        QueryWrapper q = new QueryWrapper<>();
        q.eq("username",uname);
        User user1 = userMapper.selectOne(q);

        if(user1 == null) {
            return Result.end(500,"","用户名或密码错误");
        }

        //获取用户输入的密码  并转成MD5
        String pwd = user.getPassword();
        String pwdMD5 = DigestUtils.md5DigestAsHex(pwd.getBytes());
        if(!pwdMD5.equals(user1.getPassword())) {
            return Result.end(500,"","用户名或密码错误");
        }

        //如果以上都通过，我们就将用户信息和token信息返回给客户端
        JSONObject data = new JSONObject();
        data.put("userInfo", user1);
//        JSONObject jwt = new JSONObject();
//        jwt.put("access_token",user1.getId());

        String jwt = null;
        try {
            jwt = JWTUtil.createToken(user1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        data.put("jwt",jwt);

        //将用户的信息存储在session会话中
        HttpSession session = request.getSession();
        session.setAttribute("userInfo", user1);

        return Result.end(200,data,"登陆成功");
    }

    @Override
    public Result getMenuListByRoleId(Long roleId) {
        //根据roleId获取菜单列表
        List<Menu> list = menuMapper.getMenuListByRoleId(roleId);

        List<Menu> menuList = new ArrayList<>();
        //取出父级id=-1的 作为根菜单 放在menuList中
        for(Menu menu : list) {
            if(menu.getPid() == -1) {
                menuList.add(menu);
            }
        }

        for(Menu menuFather : menuList) {
            for(Menu menu : list) {
                //提取可能是子菜单的数据
                if(menuFather.getId().equals(menu.getPid())) {

                    //如果父亲菜单没孩子就初始化一个list对象
                    if(menuFather.getChildren() == null) {
                        menuFather.setChildren(new ArrayList<>());
                    }
                    menuFather.getChildren().add(menu);
                }
            }
        }
        return Result.end(200,menuList,"成功");
    }

    @Override
    public Result getAdminListForPage(int pno, int psize, String username) {
        Page<User> p = new Page<>(pno,psize);
        Page<User> pageResult = userMapper.getAdminListForPage(p, username);

        //提取分页中的数据
        List<User> userList = pageResult.getRecords();

        JSONObject data = new JSONObject();
        data.put("list",userList);

        //传入分页相关参数
        JSONObject page = new JSONObject();
        page.put("pno",pno);
        page.put("psize",psize);
        page.put("pCount",pageResult.getPages());
        page.put("totalElements",pageResult.getTotal());
        data.put("page",page);
        return Result.end(200,data,"查询成功");
    }

    @Override
    public Result getRoleListAll() {
        //查询单表所有数据
        List<Role> roleList = roleMapper.selectList(null);

        JSONObject data = new JSONObject();
        data.put("list",roleList);
        return Result.end(200,data,"查询成功");
    }


    @Override
    public Result adminInsert(User user) {
        //初始化用户信息
        user.setFreeze(0);
        user.setInsertTime(new Date());
        user.setType(0);

        //加密密码
        String pasMD5 = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(pasMD5);

        int count = userMapper.insert(user);
        if(count > 0) {
            return Result.end(200,"","新增成功");
        }
        return Result.end(500,"","新增失败");
    }

    @Override
    public Result findAdminById(Long id) {
//        QueryWrapper q = new QueryWrapper<>();
//        q.eq("id",id);
//        User user = userMapper.selectOne(q);
        User user = userMapper.selectById(id);
        return Result.end(200,user,"查询成功");
    }

    @Override
    public Result adminUpdate(User user) {
        //加密密码
        String pasMD5 = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(pasMD5);

        int count = userMapper.updateById(user);
        if(count > 0) {
            return Result.end(200,"","新增成功");
        }
        return Result.end(500,"","新增失败");
    }

    @Override
    public Result deleteAdminById(Long id) {

        int count = userMapper.deleteById(id);
        if(count > 0) {
            return Result.end(200,"","删除成功");
        }
        return Result.end(500,"","删除失败");

    }


    @Override
    public Result updateAdminPassword(User user) {

        String oldPassword = user.getOldPassword();
        QueryWrapper q = new QueryWrapper<>();
        q.eq("username",user.getUsername());
        User user1 = userMapper.selectOne(q);
        //先确认原密码输入是否正确
        if(user1.getPassword().equals(DigestUtils.md5DigestAsHex(oldPassword.getBytes()))) {
            //若原密码正确 判断两次新输入密码是否正确
            if(user.getPassword().equals(user.getPassword1())) {
                String newPassword = user.getPassword();
                //加密新密码
                String newPasswordEncode = DigestUtils.md5DigestAsHex(newPassword.getBytes());
                user.setPassword(newPasswordEncode);
                int count = userMapper.updateById(user);
                if(count > 0) {
                    return Result.end(200,"","修改密码成功");
                }
                return Result.end(500,"","修改密码失败");
            }
            return Result.end(500,"","两次输入的密码不一致,修改密码失败");
        }
        return Result.end(500,"","原密码错误,修改密码失败");
    }

    @Override
    public Result getUserByName(String username) {
        QueryWrapper q = new QueryWrapper<>();
        q.eq("username",username);
        User user = userMapper.selectOne(q);

        return Result.end(200,user,"查询能成功");
    }

    @Override
    public Result getMenuListALl() {
        List<Menu> menuLsit= menuMapper.selectList(null);

        List<Menu> list = new ArrayList<>();
        //取出父级id=-1的 作为根菜单 放在List中
        for(Menu menu : menuLsit) {
            if(menu.getPid() == -1) {
                list.add(menu);
            }
        }
        //先取父菜单
        for(Menu menuFather : list) {
            for(Menu menu : menuLsit) {
                //提取可能是子菜单的数据
                if(menuFather.getId().equals(menu.getPid())) {
                    //如果父亲菜单没孩子就初始化一个list对象
                    if(menuFather.getChildren() == null) {
                        menuFather.setChildren(new ArrayList<>());
                    }
                    menuFather.getChildren().add(menu);
                }
            }
        }
        return Result.end(200,list,"查询成功");
    }

    @Override
    public Result insertMenuRole(MenuRole menuRole) {
        //先删除原有的数据
        QueryWrapper q = new QueryWrapper<>();
        q.eq("role_id",menuRole.getRoleId());
        menuRoleMapper.delete(q);

        //循环ids 将它与roleId关联保存到数据库中
//        for(Long id : menuRole.getIds()) {
//            MenuRole mr = new MenuRole();
//            mr.setRoleId(menuRole.getRoleId());
//            mr.setMenuId(id);
//            menuRoleMapper.insert(mr);
//        }

        Arrays.stream(menuRole.getIds()).forEach(menuId -> {
            MenuRole mr = new MenuRole();
            mr.setRoleId(menuRole.getRoleId());
            mr.setMenuId(menuId);
            menuRoleMapper.insert(mr);
        });

         return Result.end(200,"","绑定菜单成功");
    }

    @Override
    public Result insertMenu(Menu menu) {

        //设置pid = -1
        menu.setPid(Long.valueOf(-1));
        int count = menuMapper.insert(menu);
        if(count > 0) {
            return Result.end(200,"","增加成功");
        } else {
            return Result.end(500,"","增加失败");
        }
    }

    @Override
    public Result insertMenuChildren(Long pid, Menu menu) {
        int count = menuMapper.insert(menu);
        if(count > 0) {
            return Result.end(200,"","增加成功");
        } else {
            return Result.end(500,"","增加失败");
        }
    }

    @Override
    public Result findMenuById(Long id) {
        Menu menu = menuMapper.selectById(id);
        if(menu != null) {
            return Result.end(200,menu,"查询成功");
        }
        return Result.end(500,"","查询成功");
    }

    @Override
    public Result updateMenu(Menu menu) {
        int count = menuMapper.updateById(menu);
        if(count > 0) {
            return Result.end(200,"","修改成功");
        } else {
            return Result.end(500,"","修改失败");
        }
    }

    @Override
    public Result deleteMenu(Long id) {
        Menu menu = menuMapper.selectById(id);
        Long pid = menu.getPid();
        int count = 0;
        //如果pid = -1说明是父菜单  删除父菜单的时候应该同时删除他的子菜单
        if (pid == -1) {
            //先删除子菜单
            QueryWrapper<Menu> q = new QueryWrapper<>();
            q.eq("pid",id);
            int count1 = menuMapper.delete(q);
            if(count1 == 0) {
                return Result.end(500, "", "删除子菜单失败");
            }
            //删除完子菜单再删除父菜单
            count = menuMapper.deleteById(id);

        } else {
            count = menuMapper.deleteById(id);
        }

        if (count > 0) {
            return Result.end(200, "", "删除成功");
        } else {
            return Result.end(500, "", "删除失败");
        }
    }

    @Override
    public Result loginPassword(User user) {
        //根据用户名查询数据
        String uname = user.getUsername();
        QueryWrapper q = new QueryWrapper<>();
        q.eq("username",uname);
        q.eq("type",1);
        User user1 = userMapper.selectOne(q);

        if(user1 == null) {
            return Result.end(500,"","用户名或密码错误");
        }
        //获取用户输入的密码  并转成MD5
        String pwd = user.getPassword();
        String pwdMD5 = DigestUtils.md5DigestAsHex(pwd.getBytes());
        if(!pwdMD5.equals(user1.getPassword())) {
            return Result.end(500,"","用户名或密码错误");
        }
        //如果以上都通过，我们就将用户信息和token信息返回给客户端
        JSONObject data = new JSONObject();
        data.put("userInfo", user1);

        String jwt = null;
        try {
            jwt = JWTUtil.createToken(user1);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        data.put("jwt",jwt);

        return Result.end(200,data,"登陆成功");
    }

    @Override
    public Result getAddressListForPage(int pno, int psize) {
        Page<Address> p = new Page<>(pno, psize);
        Page<Address> pageResult = addressMapper.getAddressListForPage(p);

        List<Address> addressList = pageResult.getRecords();
        JSONObject data = new JSONObject();
        data.put("list",addressList);
        //传入分页相关参数
        JSONObject page = new JSONObject();
        page.put("pno",pno);
        page.put("psize",psize);
        page.put("pCount",pageResult.getPages());
        page.put("totalElements",pageResult.getTotal());
        data.put("page",page);
        return Result.end(200,data,"查询成功");

    }

    @Override
    public Result insertAddress(Address address) {
        int count = addressMapper.insert(address);
        if(count > 0) {
            return Result.end(200,"","新增成功");
        }
        return Result.end(500,"","新增失败");
    }

    @Override
    public Result findAddressById(Long addressId) {
        Address address = addressMapper.selectById(addressId);
        return Result.end(200,address,"新增成功");
    }

    @Override
    public Result updateAddress(Address address) {
        int count = addressMapper.updateById(address);
        if(count > 0) {
            return Result.end(200,"","修改成功");
        }
        return Result.end(500,"","修改失败");
    }

    @Override
    public Result deleteAddress(Long addressId) {
        int count = addressMapper.deleteById(addressId);
        if(count > 0) {
            return Result.end(200,"","删除成功");
        }
        return Result.end(500,"","删除失败");
    }

    @Override
    public Result registerUser(User user) {
        //查询该账号是否被注册
        String uname = user.getUsername();
        QueryWrapper q = new QueryWrapper<>();
        q.eq("username",uname);
        q.eq("type",1);
        User u = userMapper.selectOne(q);
        if(u != null) {
            return Result.end(500,"","用户名以被注册");
        }
        //获取用户输入的密码  并转成MD5
        String pwd = user.getPassword();
        String pwdMD5 = DigestUtils.md5DigestAsHex(pwd.getBytes());
        user.setPassword(pwdMD5);
        user.setType(1);
        user.setPhone(user.getUsername());
        user.setInsertTime(new Date());

        int count = userMapper.insert(user);
        if(count > 0) {
            return Result.end(200,"","注册成功");
        }
        return Result.end(500,"","注册失败");

    }


}
